Popular Searches
Popular Course Categories
Popular Courses

Understanding React Keys

Understanding React Keys

Lists and Dynamic Rendering

Understanding React Keys

React Keys are special attributes used to uniquely identify elements in a list. They help React determine which items have been added, removed, or reordered when the data changes. Keys are an important concept in React JS because they help React update lists correctly and efficiently.

Learn React JS: JustAcademy React JS Training Course

Register for a demo: Register for React JS Course Demo


1. What Are Keys in React?

A key is a special string or number attribute assigned to an element when rendering a collection of elements. React uses keys to identify each item among its siblings and match items between renders.

For example, an application may display a list of students, products, employees, or tasks. When a new student is added or an existing task is deleted, React uses keys to understand which list items have changed.

Example

const fruits = [
  { id: 1, name: "Apple" },
  { id: 2, name: "Banana" },
  { id: 3, name: "Orange" }
];

function FruitList() {
  return (
    <ul>
      {fruits.map((fruit) => (
        <li key={fruit.id}>{fruit.name}</li>
      ))}
    </ul>
  );
}

export default FruitList;

Output

Apple
Banana
Orange

In this example, each fruit has a unique ID. The key={fruit.id} attribute helps React identify each fruit when the list changes.


2. Why Are Keys Important in React?

React applications frequently display data collections that change over time. Keys provide stable identities for the elements in those collections, helping React reconcile the previous and updated UI.

  • Identify list items: React can distinguish one item from another.
  • Handle changes: React can recognize items that are added, removed, or reordered.
  • Support correct updates: Stable keys help React associate rendered elements and component state with the correct items.
  • Improve reconciliation: Keys provide information React uses when comparing the previous and next render trees.
  • Avoid missing-key warnings: Keys address React's warning when elements in a rendered collection lack keys.
  • Support reusable components: Keys can be assigned to components rendered from arrays.

Important: Keys help React identify elements correctly. They do not automatically make every component faster, and they are not a replacement for good rendering and performance practices.


3. How Do React Keys Work?

When React renders a list, it uses each item's key to match it with the corresponding item in a later render. A stable key helps React recognize the same item even when its position changes.

Example

Suppose the original list contains three items:

[
  { id: 1, name: "Apple" },
  { id: 2, name: "Banana" },
  { id: 3, name: "Orange" }
]

Now suppose a new item is inserted at the beginning:

[
  { id: 4, name: "Mango" },
  { id: 1, name: "Apple" },
  { id: 2, name: "Banana" },
  { id: 3, name: "Orange" }
]

Because the existing fruits retain their IDs, React can identify Apple, Banana, and Orange as the same items even though their positions have changed.

Without Stable Keys

If items are identified only by their positions, inserting an item at the beginning can cause React to associate an existing component's state with the wrong data item. This can lead to unexpected behavior in lists containing input fields, checkboxes, or other stateful elements.


4. How to Use Keys with map()

The JavaScript map() method is commonly used to render lists in React. The key should be added to the outermost JSX element returned for each item.

Example

function StudentList() {
  const students = [
    { id: 101, name: "Rahul" },
    { id: 102, name: "Priya" },
    { id: 103, name: "Amit" }
  ];

  return (
    <div>
      <h2>Student List</h2>
      <ul>
        {students.map((student) => (
          <li key={student.id}>
            {student.name}
          </li>
        ))}
      </ul>
    </div>
  );
}

export default StudentList;

Explanation

  1. The students array stores student records.
  2. The map() method processes each student.
  3. React creates one
  4. element for each student.
  5. The key={student.id} attribute identifies each student within the list.
  6. React uses those keys when reconciling changes to the rendered collection.

5. Rules for Choosing React Keys

Keys should be stable, unique among sibling elements, and associated with the same data item across renders.

Rule 1: Keys Must Be Unique Among Siblings

Each item in the same rendered list should have a distinct key. Keys do not have to be unique across the entire application.

<ul>
  <li key="apple">Apple</li>
  <li key="banana">Banana</li>
  <li key="orange">Orange</li>
</ul>

Rule 2: Keys Must Be Stable

The same item should keep the same key when the component renders again. Avoid generating a different key every time the list is rendered.

Rule 3: Prefer IDs from the Data

Database IDs or stable identifiers created when data items are added are usually the best key choices.

<li key={product.id}>{product.name}</li>

Rule 4: Do Not Use Random Keys During Rendering

Using Math.random() to create keys during every render causes the keys to change repeatedly. React may recreate components unnecessarily and reset their local state.

Rule 5: Put the Key on the Element Returned by map()

If map() returns a component, put the key on that component in the parent list.

{products.map((product) => (
  <ProductItem key={product.id} product={product} />
))}

6. Using Unique IDs as Keys

Using a stable ID is generally the recommended approach because an ID identifies the data item rather than its current position in the list.

Example

function ProductList() {
  const products = [
    { id: "p101", name: "Laptop", price: 55000 },
    { id: "p102", name: "Keyboard", price: 1200 },
    { id: "p103", name: "Mouse", price: 600 }
  ];

  return (
    <div>
      <h2>Available Products</h2>
      {products.map((product) => (
        <div key={product.id}>
          <h3>{product.name}</h3>
          <p>Price: ₹{product.price}</p>
        </div>
      ))}
    </div>
  );
}

export default ProductList;

Here, each product has a unique string ID. React can continue identifying the same product even if the list is filtered or reordered.


7. Can We Use Array Index as a Key?

Yes, an array index can be used as a key in certain situations, but it should not be the default choice for lists that change.

Example Using Index

function CityList() {
  const cities = ["Mumbai", "Pune", "Delhi"];

  return (
    <ul>
      {cities.map((city, index) => (
        <li key={index}>{city}</li>
      ))}
    </ul>
  );
}

When Can an Index Be Acceptable?

  • The list is static and will not be reordered.
  • Items will not be inserted or removed in ways that change the positions of existing items.
  • Items do not contain state or user input that could become associated with the wrong item.

When Should You Avoid an Index?

  • Items can be added or removed from the middle of the list.
  • Items can be sorted or reordered.
  • Each row contains a text field, checkbox, or stateful child component.
  • Items have stable IDs available in the data.

Best practice: Use a stable ID whenever possible. An index is not inherently invalid, but it can create bugs when a list's order or membership changes.


8. What Happens If We Do Not Provide a Key?

If you render a list of elements without keys, React commonly displays a development warning indicating that each child in a list should have a unique key prop.

Incorrect Example

function FruitList() {
  const fruits = ["Apple", "Banana", "Orange"];

  return (
    <ul>
      {fruits.map((fruit) => (
        <li>{fruit}</li>
      ))}
    </ul>
  );
}

Correct Example

function FruitList() {
  const fruits = [
    { id: 1, name: "Apple" },
    { id: 2, name: "Banana" },
    { id: 3, name: "Orange" }
  ];

  return (
    <ul>
      {fruits.map((fruit) => (
        <li key={fruit.id}>{fruit.name}</li>
      ))}
    </ul>
  );
}

Adding a key resolves the missing-key issue when the key is stable and unique among the list's siblings. Without an explicit key, React may fall back to positional matching, which is less reliable when items change order or are removed.


9. Keys with Reusable Components

React keys are also required when rendering reusable components from an array. The key belongs on the component element created by the parent list, not only on an element inside the child component.

Example

function EmployeeCard({ employee }) {
  return (
    <div>
      <h3>{employee.name}</h3>
      <p>Department: {employee.department}</p>
    </div>
  );
}

function EmployeeList() {
  const employees = [
    { id: 1, name: "Neha", department: "Development" },
    { id: 2, name: "Arjun", department: "Design" },
    { id: 3, name: "Sara", department: "Testing" }
  ];

  return (
    <div>
      {employees.map((employee) => (
        <EmployeeCard
          key={employee.id}
          employee={employee}
        />
      ))}
    </div>
  );
}

export default EmployeeList;

Important Point

The key is assigned to because that is the element returned directly by map(). Placing a key only on a nested element inside EmployeeCard does not provide a key to the parent list.


10. Why Is key Not Available as a Normal Prop?

The key attribute is reserved for React's internal use. React does not automatically pass it to the component as a regular prop. If a component needs the same ID for its own logic, pass it separately.

Incorrect Example

function ProductItem(props) {
  return <p>Product ID: {props.key}</p>;
}

<ProductItem key={product.id} product={product} />

In this example, props.key will not contain the value assigned to the special key attribute.

Correct Example

function ProductItem({ product, productId }) {
  return (
    <p>
      Product ID: {productId} - {product.name}
    </p>
  );
}

<ProductItem
  key={product.id}
  product={product}
  productId={product.id}
/>

Here, key helps React identify the component, while productId is a normal prop available to the component.


11. Using Keys with Fragments

Sometimes one item needs to render multiple sibling elements without adding an extra wrapper element to the DOM. React's Fragment can group those elements and accept a key.

Example

import { Fragment } from "react";

function StudentDetails() {
  const students = [
    { id: 1, name: "Rahul", course: "React JS" },
    { id: 2, name: "Priya", course: "JavaScript" }
  ];

  return (
    <div>
      {students.map((student) => (
        <Fragment key={student.id}>
          <h3>{student.name}</h3>
          <p>Course: {student.course}</p>
        </Fragment>
      ))}
    </div>
  );
}

export default StudentDetails;

The explicit Fragment syntax allows you to assign a key while avoiding an unnecessary wrapper element. The short fragment syntax <>... does not accept a key prop.


12. Using Keys with Conditional Lists

Keys continue to be important when lists are filtered or rendered conditionally. The key should identify the data item consistently rather than reflect its temporary position in a filtered array.

Example

function AvailableProducts() {
  const products = [
    { id: 1, name: "Laptop", available: true },
    { id: 2, name: "Tablet", available: false },
    { id: 3, name: "Phone", available: true }
  ];

  const availableProducts = products.filter(
    (product) => product.available
  );

  return (
    <ul>
      {availableProducts.map((product) => (
        <li key={product.id}>{product.name}</li>
      ))}
    </ul>
  );
}

The filter operation selects available products, and the map operation renders them. The original IDs remain stable even though some products are excluded from the displayed list.


13. Common Mistakes When Using React Keys

Mistake Problem Solution
Missing key React may show a missing-key warning. Provide a stable key to each list element.
Duplicate sibling keys React cannot reliably distinguish items with the same key. Use distinct IDs within each list.
Changing keys between renders Components may be recreated and local state may reset. Use stable identifiers from the data.
Using random keys during rendering Every render may create new identities. Avoid Math.random() for keys.
Using indexes for changing lists Component state may become associated with the wrong item. Prefer stable IDs when list items can move or change.
Putting the key on a nested child The parent list element still has no key. Put the key on the outermost element returned by map().
Trying to read props.key The special key is not passed as a normal prop. Pass the required ID separately.

14. Best Practices for React Keys

  • Prefer stable IDs from your database or application data.
  • Ensure keys are unique among siblings in the rendered collection.
  • Keep a data item's key unchanged across renders.
  • Avoid random keys and newly generated IDs during rendering.
  • Use array indexes only when the list is suitably static and has no stable ID available.
  • Place keys on the elements or components directly returned by map().
  • Pass IDs separately as normal props when child components need to access them.
  • Use an explicitly keyed Fragment when a list item needs multiple sibling elements.
  • Do not assume keys are a global identifier; their uniqueness requirement applies to siblings.
  • Test lists that allow insertion, deletion, sorting, and editing to make sure state stays with the correct item.

15. Difference Between React Key and HTML id

Feature React key HTML id
Purpose Helps React identify elements during reconciliation. Identifies an HTML element in the document.
Visibility in HTML Not rendered as a normal HTML attribute. Rendered as the element's id attribute.
Access in component props Not available as a regular prop. Can be passed and used as a normal prop.
Uniqueness Must be unique among siblings in the collection. Should be unique within the HTML document.
Typical usage
  • Remember: React's key and HTML's id serve different purposes. You may use the same underlying data ID for both when appropriate, but one does not replace the other.


    16. Practical Project: Task List with React Keys

    Create a task list that displays each task's title and status. Each task should have a stable ID used as its React key.

    Example Code

    function TaskList() {
      const tasks = [
        { id: 1, title: "Learn JSX", completed: true },
        { id: 2, title: "Understand React Keys", completed: false },
        { id: 3, title: "Build a React Project", completed: false }
      ];
    
      return (
        <div>
          <h2>My Tasks</h2>
          <ul>
            {tasks.map((task) => (
              <li key={task.id}>
                {task.title} - {task.completed ? "Completed" : "Pending"}
              </li>
            ))}
          </ul>
        </div>
      );
    }
    
    export default TaskList;

    Learning Outcomes

    • Understand how React keys work in a real list.
    • Use unique IDs to identify task items.
    • Render object data with map().
    • Display conditional content for task status.
    • Understand why stable keys matter when a list changes.

    17. Interview Questions and Answers

    Q1. What are keys in React?

    Answer: Keys are special attributes used to identify elements among siblings in a rendered collection. They help React match list items between renders.

    Q2. Why are keys important in React?

    Answer: Keys help React identify which items have been added, removed, or reordered and associate component instances with the correct items.

    Q3. What happens if we do not provide keys?

    Answer: React commonly shows a development warning for missing keys. Without stable keys, React may rely on positional matching, which can lead to incorrect state associations when the list changes.

    Q4. Can we use array indexes as keys?

    Answer: Yes, for suitably static lists. For lists that may be reordered, inserted into, or deleted from, stable IDs are preferred.

    Q5. Can keys be duplicated?

    Answer: Keys should be unique among sibling elements. Duplicate keys can make it difficult for React to identify items correctly.

    Q6. Are keys passed to child components as props?

    Answer: No. React reserves the key attribute for its own use. Pass the item's ID through a separate prop if the component needs it.

    Q7. What is the difference between key and id?

    Answer: A React key is used internally for reconciliation, while an HTML ID identifies an element in the document and can be used for styling, scripting, or accessibility relationships.

    Q8. Why should we avoid Math.random() for keys?

    Answer: Random values change between renders, making React treat existing items as new ones. This can cause unnecessary remounts and loss of local component state.

    Q9. Where should the key be placed when using a reusable component?

    Answer: Put the key on the component element returned directly by the parent's map() call.

    Q10. Can React Fragments have keys?

    Answer: Yes. Use the explicit syntax. The short <>... syntax does not accept a key.


    18. Practice Exercises

    1. Create a list of five students and assign each student a unique key.
    2. Create a product list using product IDs as keys.
    3. Render employee cards using a separate reusable component and stable keys.
    4. Remove an item from a list and observe how stable IDs preserve correct item identity.
    5. Sort a list and compare stable ID keys with index keys.
    6. Create a task list with checkboxes and test how list keys affect state when items are reordered.
    7. Render multiple sibling elements for each item using a keyed React Fragment.

    19. Quick Revision Checklist

    • Understand what React keys are and why they are required for rendered collections.
    • Know how to assign keys when using map().
    • Prefer stable and unique IDs from the data.
    • Understand the limitations of array indexes as keys.
    • Avoid random keys that change during rendering.
    • Know that keys are not passed as normal component props.
    • Understand the difference between React keys and HTML IDs.
    • Know how to assign keys to reusable components and Fragments.
    • Practice rendering lists that can be added to, deleted from, or reordered.

    20. Conclusion

    Understanding React Keys is essential for building reliable React JS applications. Keys help React identify items within a list and reconcile changes when data is updated. Using stable, unique identifiers helps prevent state-related issues in changing lists and makes the rendering logic easier to maintain. Always place keys on the elements returned by list-rendering expressions, and remember that keys serve a different purpose from ordinary props and HTML IDs.

    Learn more through the JustAcademy React JS Training Course or register for a React JS course demo.

    whatsapp